import { XStream } from '@ant-design/x';
import type { ChatHistory } from './types';
import request from '@/utils/request';
import { STREAM_EVENT_RESPONSE_TYPE } from '@/state/common';

const logStyle = 'color: lightgreen; background-color: #000;';
const token = localStorage.getItem('token');
const Log = (...args: any[]) => {
  console.log('%c[流式对话]', logStyle, ...args);
};

/** 将流合并转换为文本 */
export async function readableStreamToText(data: any) {
  const response: ChatHistory = {
    key: '',
    role: 'assistant',
    content: '',
    loading: false,
  };
  for await (const chunk of XStream({
    readableStream: data.body,
  })) {
    try {
      const obj = chunk;
      if (obj.event === ' done') {
        break;
      }
      const parsedData = JSON.parse(JSON.parse(obj.data));
      response.key = parsedData.chat_id;
      Log(`${STREAM_EVENT_RESPONSE_TYPE[obj.event].name}：`, parsedData);

      if (parsedData.content && obj.event === ' conversation.message.delta') {
        response.content += parsedData.content;
        response.role = parsedData.role;
      }
    } catch (err) {
      console.error(err);
      throw Error();
    }
  }
  return response;
}

/** 单轮对话 */
// export async function singleChat(message: string) {
//   const res = await fetch('/api/v1/interview/chat', {
//     method: 'POST',
//     body: JSON.stringify({
//       data: message,
//     }),
//     headers: {
//       Authorization: `Bearer ${token}`,
//       'Content-Type': 'application/json',
//     },
//   });
//   return readableStreamToText(res);
// }

/** 面试对话 */
export async function reviewChat(data: { answer: string; session_id: number }) {
  const res = await fetch('/api/v1/interview/chat/agent', {
    method: 'POST',
    body: JSON.stringify(data),
    headers: {
      Authorization: `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
  });
  return readableStreamToText(res);
}

/** 获取新的session_id */
export async function getNewSessionId() {
  return request.post<{ session_id: number }>({
    url: '/api/v1/interview/chat/new',
  });
}

/** 创建面试 */
export async function createInterview(data: {
  session_id: number;
  hc: string;
  pdf_url: string;
  question_num?: number;
  level?: number;
}) {
  const res = await fetch('/api/v1/interview/new_interview', {
    method: 'POST',
    body: JSON.stringify(data),
    headers: {
      Authorization: `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
  });
  return readableStreamToText(res);
}
